package com.orangelife.mobile.util;

import android.app.AlertDialog;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.common.sp.AppSp;
import com.common.sp.SharedPreferUtil;
import com.curry.android.http.OrangeDataHandler;
import com.curry.android.http.OrangeErrorHandler;
import com.curry.android.http.VolleyHttpUtil;
import com.curry.android.util.*;
import com.curry.android.util.ToastHelper;
import com.curry.orangelife.mobile.R;
import com.orangelife.mobile.constants.CommonURL;
import com.orangelife.mobile.download.DownloadProgressListener;
import com.orangelife.mobile.download.FileDownloader;

import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * APK更新
 */
public class UpdateManager {
    private Context mContext;

    // 返回的安装包url
    private String apkUrl = "";

    private Dialog noticeDialog;

    private Dialog downloadDialog;
    /* 下载包安装路径 */
    private static final String savePath = "/sdcard/OrangeLife/";

    private static final String saveFileName = savePath + "orangelife.apk";

    /* 进度条与通知ui刷新的handler和msg常量 */
    private ProgressBar mProgress;

    private static final int FILE_LENGTH = 0;

    private static final int DOWN_UPDATE = 1;

    private static final int DOWN_OVER = 2;

    private int progress;

    private Thread downLoadThread;

    private boolean interceptFlag = false;

    private Button btnUpdate;
    private Button btnCancel;
    private Button btnSure;
    private TextView tvContent;
    private TextView tvTitle;
    private LinearLayout llUpdate, llShowInfo;
    private AlertDialog dialog;
    private File dir;
    private String versionInfo = "暂无版本信息";

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case FILE_LENGTH:
                    int size = msg.getData().getInt("size");
                    mProgress.setProgress(size);
                    if (mProgress.getProgress() == mProgress.getMax()) {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                            installApk();
                        }
                    }
                    break;
                case DOWN_UPDATE:
                    mProgress.setProgress(progress);
                    break;
                case DOWN_OVER:
                    if (dialog != null && dialog.isShowing()) {
                        dialog.dismiss();
                        installApk();
                    }
                    break;
                default:
                    break;
            }
        }

        ;
    };

    public UpdateManager(Context context, boolean isToast) {
        this.mContext = context;
        getVersionCode(isToast);
    }

    private void getVersionCode(final boolean isToast) {
        HashMap<String, String> map = new HashMap<>();
        map.put("type", "2");
        map.put("appType", "1");
        VolleyHttpUtil.getInstance().getWithCallback(CommonURL.VERSION, map, new VolleyHttpUtil.ResponseCallBack() {
            @Override
            public void handleResponse(JSONObject jsonObject, int i) {
                boolean isSuccess = false;
                if (OrangeErrorHandler.getInstance().isSuccess(jsonObject)) {
                    Map<String, Object> map = OrangeDataHandler.getMapWithEntityNoGson(jsonObject);
                    if (map != null && map.size() > 0) {
                        isSuccess = true;
                        String newVersion = String.valueOf(map.get("version"));
                        String minVersion = String.valueOf(map.get("minVersion"));
                        String url = String.valueOf(map.get("url"));
                        versionInfo = String.valueOf(map.get("remark"));
                        check(newVersion, minVersion, url, isToast);
                    }
                }
                if (isToast && !isSuccess) {
                    ToastHelper.getInstance()._toast("获取版本信息失败");
                }
            }
        });
    }

    private void check(String newVersion, String minVersion, String url, boolean isToast) {
        String currentVer = SystemInfoUtil.getVersionName(mContext);
        String isForce = "0";
        if (isNew(minVersion, currentVer)) {/*如果大于最低使用版本，则强制更新*/
            isForce = "1";
            CleanCacheUtils.getInstance().init(mContext);
            CleanCacheUtils.getInstance().cleanCache();
            checkUpdateInfo(url, isForce, versionInfo, newVersion);
        } else if (isNew(newVersion, currentVer)) {
            checkUpdateInfo(url, isForce, versionInfo, newVersion);
        } else if (newVersion.equals(currentVer)) {
            if (isToast) {
                ToastHelper.getInstance()._toast("当前已是最新版本！");
            }
            if (AppSp.isShowUpdateInfo()) {
                //checkUpdateInfo(url, versionInfo, newVersion); 3.8 关闭 更新成功 再次进入显示更新信息
            }
        }
    }

    /**
     * @param apkUrl
     */
    public void checkUpdateInfo(String apkUrl, String info, String title) {
        this.apkUrl = apkUrl;
        showNoticeDialog(2, info, title);
    }

    public void checkUpdateInfo(String apkUrl, String isForce, String info, String title) {
        this.apkUrl = apkUrl;
        if (isForce.equals("1")) {
            showNoticeDialog(1, info, title);
        } else if (isForce.equals("0")) {
            showNoticeDialog(0, info, title);
        }
    }

    private void showNoticeDialog(int isForce, String info, String title) {
        final AlertDialog dialog2 = new AlertDialog.Builder(mContext).create();
        View v = LayoutInflater.from(mContext).inflate(R.layout.umeng_update_dialog, null);
        llUpdate = (LinearLayout) v.findViewById(R.id.llUpdate);
        llShowInfo = (LinearLayout) v.findViewById(R.id.llShowInfo);
        tvContent = (TextView) v.findViewById(R.id.umeng_update_content);
        tvTitle = (TextView) v.findViewById(R.id.tvUpdateTitle);
        btnSure = (Button) v.findViewById(R.id.btnConfirm);
        btnCancel = (Button) v.findViewById(R.id.umeng_update_id_cancel);
        tvTitle.setText(title + "版本更新");

        switch (isForce) {
            case 0:
                tvContent.setText(info);
                llUpdate.setVisibility(View.VISIBLE);
                llShowInfo.setVisibility(View.GONE);
            /*强制更新，禁止取消*/
                btnCancel.setVisibility(View.VISIBLE);
                btnCancel.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        if (dialog2 != null && dialog2.isShowing())
                            dialog2.dismiss();
                    }
                });
                break;
            case 1:
                llUpdate.setVisibility(View.VISIBLE);
                llShowInfo.setVisibility(View.GONE);
                tvContent.setText(info);
                btnCancel.setVisibility(View.GONE);
                break;
            case 2:
                llUpdate.setVisibility(View.GONE);
                llShowInfo.setVisibility(View.VISIBLE);
                tvContent.setText(info);
                break;
            default:
                break;
        }
        dialog2.setCancelable(false);
        dialog2.setView(v, 0, 0, 0, 0);
        dialog2.show();
        btnUpdate = (Button) v.findViewById(R.id.umeng_update_id_ok);
        btnUpdate.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (dialog2.isShowing()) {
                    dialog2.dismiss();
                }
                showDownloadDialog();
//				Intent intent = new Intent(mContext,UpdateShow.class);
//				Bundle bundle = new Bundle();
//				intent.putExtras(bundle);
//				mContext.startActivity(intent);
            }
        });
        btnSure.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                AppSp.setIsShowUpdateInfo(false);
                if (dialog2 != null && dialog2.isShowing()) {
                    dialog2.dismiss();
                }
            }
        });
    }

    private void showDownloadDialog() {
        dialog = new AlertDialog.Builder(mContext).create();
//		builder.setTitle("版本更新");

        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.progress);

        dialog.setView(v, 0, 0, 0, 0);
        dialog.setCancelable(false);
        dialog.show();
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            dir = new File(savePath);
            download(apkUrl, dir);
        }
//		downloadApk();	
    }

    private Runnable mdownApkRunnable = new Runnable() {
        @Override
        public void run() {
            try {
                URL url = new URL(apkUrl);

                HttpURLConnection conn = (HttpURLConnection) url
                        .openConnection();
                conn.setRequestProperty("Accept-Encoding", "identity");
                conn.connect();
                int length = conn.getContentLength();
                InputStream is = conn.getInputStream();

                File file = new File(savePath);
                if (!file.exists()) {
                    file.mkdir();
                }
                String apkFile = saveFileName;
                File ApkFile = new File(apkFile);
                FileOutputStream fos = new FileOutputStream(ApkFile);

                int count = 0;
                byte buf[] = new byte[1024];

                do {
                    int numread = is.read(buf);
                    count += numread;
                    progress = (int) (((float) count / length) * 100);
                    // 更新进度
                    mHandler.sendEmptyMessage(DOWN_UPDATE);
                    if (numread <= 0) {
                        // 下载完成通知安装
                        mHandler.sendEmptyMessage(DOWN_OVER);
                        break;
                    }
                    fos.write(buf, 0, numread);
                } while (!interceptFlag);// 点击取消就停止下载.

                fos.close();
                is.close();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    };

    /**
     * 下载apk
     */
    private void downloadApk() {
        downLoadThread = new Thread(mdownApkRunnable);
        downLoadThread.start();
    }

    private void download(final String path, final File dir) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                FileDownloader loader = new FileDownloader(mContext, path, dir, 3);
                int length = loader.getFileSize();
                mProgress.setMax(length);
                try {
                    loader.download(new DownloadProgressListener() {
                        @Override
                        public void onDownloadSize(int size) {
                            Message msg = new Message();
                            msg.what = FILE_LENGTH;
                            msg.getData().putInt("size", size);
                            mHandler.sendMessage(msg);
                        }
                    });
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }).start();
    }

    /**
     * 安装apk
     */
    private void installApk() {
        File apkfile = new File(savePath + FileDownloader.filename);
        if (!apkfile.exists()) {
            return;
        }
        SharedPreferUtil.getInstance().clearAll();
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
                "application/vnd.android.package-archive");
        mContext.startActivity(i);
        AppSp.setVersionInfo(versionInfo);
    }

    private boolean isNew(String newVersion, String oldVersion) {
        Pattern pattern = Pattern.compile("^(([0-9]+)\\.)*(([0-9]+|[a-z]+))$");


        if (!pattern.matcher(newVersion).matches() || !pattern.matcher(oldVersion).matches()) {
            return false;
        }
        String[] newVer = newVersion.split("\\.");
        String[] oldVer = oldVersion.split("\\.");

        for (int i = 0; i < newVer.length; i++) {
            if (newVer[i].compareTo(oldVer[i]) > 0) {
                return true;
            }
            if (newVer[i].compareTo(oldVer[i]) < 0) {
                return false;
            }
            if (newVer.length > oldVer.length) {
                return true;
            }
        }

        return false;

    }
}
